#pragma GCC optimize(2)
#include <iostream>
#include <queue>
#include <map>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <unordered_set>
#include <bitset>
#define F first
#define S second
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;

void solve()
{
	ll m,k,a1,a2;
	cin>>m>>k>>a1>>a2;
	if(k<=1)
	{
		cout<<m-(a1+a2*k)<<endl;
		return ;
	}
	else
	{
		ll cnt=m/k;
		
		ll ans=0;
		ll r=0;
		m=m-cnt*k;
//		cout<<m<<endl;
		ans+=max(cnt-a2,0ll);
		if(m)
		{
			if(a1>=m) a1-=m,m=0;
			else
			{
				ans+=(m-a1);
				cout<<ans<<endl;
				return ;
			}
		}
		ll num=a1/k;
//		cout<<num<<endl;
		if(a2>=cnt)
		{
			cout<<ans<<endl;
		}
		else
		{
			ans-=min(num,cnt-a2);
			cout<<ans<<endl;
		}	

	}
}
int main()
{
	IOS;
	int T=1;
	cin>>T;

	while(T--)
	{
		solve();
	}

	return 0;
}

